<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules, identifyCode, tableIdentify } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import VerCode from "@/components/VerCode/index.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { initRouter } from "@/router/utils";
import { throttle, debounce } from "@pureadmin/utils";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import doorlock from "@iconify-icons/ri/door-lock-line";

// defineOptions({
//   name: "Login"
// });
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: "",
  qrcode: ""
});

const onLogin = debounce(async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({
          password: ruleForm.password,
          username: ruleForm.username
        })
        .then(res => {
          // console.log("login", res);
          if (res.success) {
            // 获取后端路由
            initRouter().then(() => {
              if (res.data.roles[0] == "admin") {
                router.push("/Welcome");
              } else if (res.data.roles[0] == "tea") {
                router.push("/Welcome");
              } else {
                location.href = "/"
                // router.push("/stuindex");
              }
              message("登录成功", { type: "success" });
            });
          } else {
            tableIdentify();
            ruleForm.qrcode = "";
            message(res.msg, { type: "error" });
            loading.value = false;
          }
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
}, 300)


/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "NumpadEnter" || code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  tableIdentify();
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <div class="login-header">
      <img :src="bg" />
    </div>
    <div class="login-container">
      <div class="login-box">
        <div class="login-form">
          <Motion class="login-title">
            <h2 class="outline-none">用户登录</h2>
            <!-- <p>Welcome to login</p> -->
          </Motion>

          <el-form ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
            <Motion :delay="100">
              <el-form-item prop="username">
                <el-input class="usercontent" clearable v-model="ruleForm.username" placeholder="账号"
                  :prefix-icon="useRenderIcon(User)" />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input class="usercontent" clearable type="password" v-model="ruleForm.password" placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)" />
              </el-form-item>
            </Motion>
            <Motion :delay="150">
              <el-form-item prop="qrcode">
                <el-input placeholder="验证码" class="isqrcode" v-model="ruleForm.qrcode"
                  :prefix-icon="useRenderIcon(doorlock)">
                  <template #append>
                    <ver-code @click="tableIdentify" :contentHeight="58" :identifyCode="identifyCode" />
                  </template>
                </el-input>
                <span class="tab_qrcode">点击图片切换</span>
              </el-form-item>
            </Motion>

            <Motion :delay="250" style="text-align: left;">
              <el-button class="w-full mt-4 login-btn" size="default" type="primary" :loading="loading"
                @click="onLogin(ruleFormRef)">
                登&nbsp;&nbsp;&nbsp;&nbsp;录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
    <div class="login-buttom">
      <ul>
        <img src="@/assets/studen/images/zs-wximg.png" />
      </ul>
      <ul>
        <li>建议使用谷歌浏览器，获得更快响应速度 版本号：V1.0_200107 </li>
        <li>版权所有©深圳智盛信息技术股份有限公司 &nbsp;&nbsp; 咨询电话：400-830-1192&nbsp;&nbsp; 咨询QQ：4008889026</li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped></style>
